package net.tngou.tpage.dao;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;

import net.tngou.tpage.jdbc.PageUtil;
import net.tngou.tpage.jdbc.QueryHelper;
import net.tngou.tpage.pojo.Login;
import net.tngou.tpage.pojo.POJO;
import net.tngou.tpage.pojo.User;
import net.tngou.tpage.util.StringUtil;







public class UserDao extends BaseDao{

	
	
	/**
	 * 更新用登录
	 * @param access_token
	 * @param user
	 */
	public void updateLogin(String access_token, User user) {
		
		Timestamp timestamp=new  Timestamp(DateUtils.addDays(new Date(), 30).getTime());
		Login bean = new Login();
		String filter="user="+user.getId();
		Login login = bean.get(filter);
		if(login!=null)
		{
			login.setExpiredtime(timestamp);
			if(!access_token.equals(user.getAccess_token()))login.setAccess_token(access_token);
			login.update();
			
		}else
		{
			login = new Login();
			login.setExpiredtime(timestamp);//
			login.setAccess_token(access_token);
			login.setUser(user.getId());
			login.save();
		}
		
	}

	/**
	 * 查询用户
	 * @param page 当前页
	 * @param size 大小
	 * @param main 实体
	 * @param role 角色
	 * @param keyword 关键词 
	 * @return
	 */
	public PageUtil getPage(int page,int size,long main,long role,String keyword) {
		
		List<?> list=new ArrayList<>();
		int total=0;
		String sql_r="SELECT u.id,u.account,u.name,u.phone,u.email,u.position,u.time";//对象
		String sql_t="SELECT COUNT(id)";//总数
		String sql_o=" ORDER BY id DESC";//排序
		String sql = " FROM `"+POJO.DABASE+"_user` u WHERE main=? AND role=?";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql=sql+ " AND ( name LIKE ? OR account LIKE ? OR phone LIKE ? OR email LIKE ? OR position LIKE ?)";
			Object[] params={main,role,keyword+"%",keyword+"%",keyword+"%",keyword+"%",keyword+"%"};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);			
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}else
		{
			Object[] params={main,role};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}
		
		return new PageUtil(list, page, size, total);
	}
	
	
	
}
